<template>
  <n-card class="loadout-card" :class="{ 'invalid-loadout': !loadout.within_target }">
    <!-- 卡片头部 -->
    <template #header>
      <div class="loadout-header">
        <div class="header-left">
          <n-tag :type="loadout.within_target ? 'success' : 'warning'" size="small">
            {{ loadout.within_target ? '预算内' : '超预算' }}
          </n-tag>
          <span class="total-value">{{ formatPrice(loadout.total_cost) }}</span>
          <span class="budget-ratio">{{ (loadout.budget_ratio * 100).toFixed(1) }}%</span>
        </div>
        <div class="header-right">
          <n-tag type="info" size="small">{{ loadout.style }}</n-tag>
        </div>
      </div>
    </template>

    <!-- 简化的装备配置表格 -->
    <div class="equipment-table">
      <!-- 主武器 -->
      <div v-if="weaponData" class="equipment-row weapon-row">
        <div class="equipment-type">主武器</div>
        <div class="equipment-image">
          <n-image
            :src="weaponData.pic"
            :alt="weaponData.object_name"
            width="50"
            height="50"
            object-fit="contain"
            fallback-src="/images/weapon-placeholder.png"
          />
        </div>
        <div class="equipment-info">
          <div class="equipment-name">{{ weaponData.object_name }}</div>
          <div class="equipment-details">
            <span class="detail-item">等级: {{ weaponData.grade }}</span>
            <span class="detail-item">分类: {{ weaponData.second_class_cn }}</span>
            <span class="detail-item">重量: {{ weaponData.weight }}kg</span>
            <span class="detail-item">尺寸: {{ weaponData.length }}×{{ weaponData.width }}</span>
          </div>
        </div>
        <div class="equipment-price">
          <div class="current-price">{{ formatPrice(weaponData.current_price) }}</div>
          <div class="price-change" :class="getPriceChangeClass(weaponData.price_change_percent)">
            {{ formatPriceChange(weaponData.price_change_percent) }}
          </div>
        </div>
      </div>

      <!-- 配件 -->
      <div v-for="(accessory, index) in accessoriesData" :key="index" class="equipment-row accessory-row">
        <div class="equipment-type">配件</div>
        <div class="equipment-image">
          <n-image
            :src="accessory.pic"
            :alt="accessory.object_name"
            width="40"
            height="40"
            object-fit="contain"
            fallback-src="/images/accessory-placeholder.png"
          />
        </div>
        <div class="equipment-info">
          <div class="equipment-name">{{ accessory.object_name }}</div>
          <div class="equipment-details">
            <span class="detail-item">等级: {{ accessory.grade }}</span>
            <span class="detail-item">分类: {{ accessory.second_class_cn }}</span>
            <span class="detail-item">重量: {{ accessory.weight }}kg</span>
            <span class="detail-item">尺寸: {{ accessory.length }}×{{ accessory.width }}</span>
          </div>
        </div>
        <div class="equipment-price">
          <div class="current-price">{{ formatPrice(accessory.current_price) }}</div>
          <div class="price-change" :class="getPriceChangeClass(accessory.price_change_percent)">
            {{ formatPriceChange(accessory.price_change_percent) }}
          </div>
        </div>
      </div>

      <!-- 头盔 -->
      <div v-if="helmetData" class="equipment-row protection-row">
        <div class="equipment-type">头盔</div>
        <div class="equipment-image">
          <n-image
            :src="helmetData.pic"
            :alt="helmetData.object_name"
            width="40"
            height="40"
            object-fit="contain"
            fallback-src="/images/helmet-placeholder.png"
          />
        </div>
        <div class="equipment-info">
          <div class="equipment-name">{{ helmetData.object_name }}</div>
          <div class="equipment-details">
            <span class="detail-item">等级: {{ helmetData.grade }}</span>
            <span class="detail-item">分类: {{ helmetData.second_class_cn }}</span>
            <span class="detail-item">重量: {{ helmetData.weight }}kg</span>
            <span class="detail-item">尺寸: {{ helmetData.length }}×{{ helmetData.width }}</span>
          </div>
        </div>
        <div class="equipment-price">
          <div class="current-price">{{ formatPrice(helmetData.current_price) }}</div>
          <div class="price-change" :class="getPriceChangeClass(helmetData.price_change_percent)">
            {{ formatPriceChange(helmetData.price_change_percent) }}
          </div>
        </div>
      </div>

      <!-- 护甲 -->
      <div v-if="armorData" class="equipment-row protection-row">
        <div class="equipment-type">护甲</div>
        <div class="equipment-image">
          <n-image
            :src="armorData.pic"
            :alt="armorData.object_name"
            width="40"
            height="40"
            object-fit="contain"
            fallback-src="/images/armor-placeholder.png"
          />
        </div>
        <div class="equipment-info">
          <div class="equipment-name">{{ armorData.object_name }}</div>
          <div class="equipment-details">
            <span class="detail-item">等级: {{ armorData.grade }}</span>
            <span class="detail-item">分类: {{ armorData.second_class_cn }}</span>
            <span class="detail-item">重量: {{ armorData.weight }}kg</span>
            <span class="detail-item">尺寸: {{ armorData.length }}×{{ armorData.width }}</span>
          </div>
        </div>
        <div class="equipment-price">
          <div class="current-price">{{ formatPrice(armorData.current_price) }}</div>
          <div class="price-change" :class="getPriceChangeClass(armorData.price_change_percent)">
            {{ formatPriceChange(armorData.price_change_percent) }}
          </div>
        </div>
      </div>

      <!-- 背包 -->
      <div v-if="backpackData" class="equipment-row protection-row">
        <div class="equipment-type">背包</div>
        <div class="equipment-image">
          <n-image
            :src="backpackData.pic"
            :alt="backpackData.object_name"
            width="40"
            height="40"
            object-fit="contain"
            fallback-src="/images/backpack-placeholder.png"
          />
        </div>
        <div class="equipment-info">
          <div class="equipment-name">{{ backpackData.object_name }}</div>
          <div class="equipment-details">
            <span class="detail-item">等级: {{ backpackData.grade }}</span>
            <span class="detail-item">分类: {{ backpackData.second_class_cn }}</span>
            <span class="detail-item">重量: {{ backpackData.weight }}kg</span>
            <span class="detail-item">尺寸: {{ backpackData.length }}×{{ backpackData.width }}</span>
          </div>
        </div>
        <div class="equipment-price">
          <div class="current-price">{{ formatPrice(backpackData.current_price) }}</div>
          <div class="price-change" :class="getPriceChangeClass(backpackData.price_change_percent)">
            {{ formatPriceChange(backpackData.price_change_percent) }}
          </div>
        </div>
      </div>

      <!-- 胸挂 -->
      <div v-if="chestRigData" class="equipment-row protection-row">
        <div class="equipment-type">胸挂</div>
        <div class="equipment-image">
          <n-image
            :src="chestRigData.pic"
            :alt="chestRigData.object_name"
            width="40"
            height="40"
            object-fit="contain"
            fallback-src="/images/chest-rig-placeholder.png"
          />
        </div>
        <div class="equipment-info">
          <div class="equipment-name">{{ chestRigData.object_name }}</div>
          <div class="equipment-details">
            <span class="detail-item">等级: {{ chestRigData.grade }}</span>
            <span class="detail-item">分类: {{ chestRigData.second_class_cn }}</span>
            <span class="detail-item">重量: {{ chestRigData.weight }}kg</span>
            <span class="detail-item">尺寸: {{ chestRigData.length }}×{{ chestRigData.width }}</span>
          </div>
        </div>
        <div class="equipment-price">
          <div class="current-price">{{ formatPrice(chestRigData.current_price) }}</div>
          <div class="price-change" :class="getPriceChangeClass(chestRigData.price_change_percent)">
            {{ formatPriceChange(chestRigData.price_change_percent) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 汇总信息 -->
    <div class="summary-section">
      <n-grid :cols="4" :x-gap="12">
        <n-grid-item>
          <n-statistic label="武器价值" :value="weaponData?.current_price || 0" suffix="" size="small" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="配件价值" :value="accessoriesValue" suffix="" size="small" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="防护价值" :value="protectionValue" suffix="" size="small" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="预算使用率" :value="(loadout.budget_ratio * 100).toFixed(1)" suffix="%" size="small" />
        </n-grid-item>
      </n-grid>
    </div>
  </n-card>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import type { TacticalLoadout, TacticalItem } from '@/types/tactical'

interface Props {
  loadout: TacticalLoadout
}

const props = defineProps<Props>()

// 数据解析函数
const parseItemData = (itemArray: [string, string, number] | null): TacticalItem | null => {
  if (!itemArray) return null
  
  try {
    // 解析ItemInfo字符串，提取object_name和其他信息
    const itemInfoStr = itemArray[0]
    const priceDataStr = itemArray[1]
    const avgPrice = itemArray[2]
    
    // 使用正则表达式提取object_name
    const nameMatch = itemInfoStr.match(/object_name='([^']+)'/)
    const objectIdMatch = itemInfoStr.match(/object_id=(\d+)/)
    const gradeMatch = itemInfoStr.match(/grade=(\d+)/)
    const picMatch = itemInfoStr.match(/pic='([^']+)'/)
    const descMatch = itemInfoStr.match(/desc='([^']*)'/)
    const categoryMatch = itemInfoStr.match(/category_id=(\d+)/)
    const weightMatch = itemInfoStr.match(/weight=([\d.]+)/)
    const lengthMatch = itemInfoStr.match(/length=(\d+)/)
    const widthMatch = itemInfoStr.match(/width=(\d+)/)
    const primaryClassMatch = itemInfoStr.match(/primary_class='([^']+)'/)
    const secondClassMatch = itemInfoStr.match(/second_class_cn='([^']+)'/)
    
    // 解析价格数据
    const currentPriceMatch = priceDataStr.match(/current_price=([\d.]+)/)
    const price24hAgoMatch = priceDataStr.match(/price_24h_ago=([\d.]+)/)
    const priceChangeMatch = priceDataStr.match(/price_change_24h=([-\d.]+)/)
    const priceChangePercentMatch = priceDataStr.match(/price_change_percent=([-\d.]+)/)
    
    return {
      object_id: objectIdMatch ? parseInt(objectIdMatch[1]) : 0,
      object_name: nameMatch ? nameMatch[1] : '未知装备',
      category_id: categoryMatch ? parseInt(categoryMatch[1]) : 0,
      grade: gradeMatch ? parseInt(gradeMatch[1]) : 1,
      pic: picMatch ? picMatch[1] : '',
      current_price: currentPriceMatch ? parseFloat(currentPriceMatch[1]) : avgPrice,
      price_24h_ago: price24hAgoMatch ? parseFloat(price24hAgoMatch[1]) : 0,
      price_change_24h: priceChangeMatch ? parseFloat(priceChangeMatch[1]) : 0,
      price_change_percent: priceChangePercentMatch ? parseFloat(priceChangePercentMatch[1]) : 0,
      has_price_data: true,
      primary_class: primaryClassMatch ? primaryClassMatch[1] : '',
      second_class_cn: secondClassMatch ? secondClassMatch[1] : '',
      desc: descMatch ? descMatch[1] : '',
      weight: weightMatch ? parseFloat(weightMatch[1]) : 0,
      length: lengthMatch ? parseInt(lengthMatch[1]) : 1,
      width: widthMatch ? parseInt(widthMatch[1]) : 1
    }
  } catch (error) {
    console.error('解析装备数据失败:', error)
    return null
  }
}

// 计算属性
const weaponData = computed(() => parseItemData(props.loadout.weapon))

const accessoriesData = computed(() => {
  return props.loadout.accessories
    ?.map(acc => parseItemData(acc))
    .filter(Boolean) as TacticalItem[] || []
})

const helmetData = computed(() => parseItemData(props.loadout.helmet))
const armorData = computed(() => parseItemData(props.loadout.armor))
const backpackData = computed(() => parseItemData(props.loadout.backpack))
const chestRigData = computed(() => parseItemData(props.loadout.chest_rig))

const accessoriesValue = computed(() => {
  return accessoriesData.value.reduce((total, accessory) => {
    return total + (accessory.current_price || 0)
  }, 0)
})

const protectionValue = computed(() => {
  let total = 0
  if (helmetData.value) total += helmetData.value.current_price || 0
  if (armorData.value) total += armorData.value.current_price || 0
  if (backpackData.value) total += backpackData.value.current_price || 0
  if (chestRigData.value) total += chestRigData.value.current_price || 0
  return total
})

// 格式化价格函数
const formatPrice = (price: number) => {
  return price.toLocaleString('zh-CN')
}

// 格式化价格变化
const formatPriceChange = (percent: number) => {
  if (percent > 0) return `+${percent.toFixed(1)}%`
  if (percent < 0) return `${percent.toFixed(1)}%`
  return '0%'
}

// 获取价格变化样式类
const getPriceChangeClass = (percent: number) => {
  if (percent > 0) return 'price-up'
  if (percent < 0) return 'price-down'
  return 'price-same'
}
</script>

<style scoped>
.loadout-card {
  border: 1px solid var(--border-color);
  transition: all 0.3s ease;
}

.loadout-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.invalid-loadout {
  border-color: var(--error-color);
  background-color: rgba(var(--error-color-rgb), 0.02);
}

.loadout-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.total-value {
  font-weight: 600;
  color: var(--primary-color);
  font-size: 16px;
}

.budget-ratio {
  font-size: 14px;
  color: var(--text-color-2);
}

/* 装备表格样式 */
.equipment-table {
  margin-bottom: 16px;
}

.equipment-row {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 12px 0;
  border-bottom: 1px solid var(--border-color);
}

.equipment-row:last-child {
  border-bottom: none;
}

.weapon-row {
  background-color: rgba(var(--primary-color-rgb), 0.05);
  padding: 16px;
  border-radius: 8px;
  border-bottom: none;
  margin-bottom: 8px;
}

.accessory-row {
  padding-left: 16px;
}

.protection-row {
  padding-left: 16px;
  background-color: rgba(var(--success-color-rgb), 0.02);
}

.equipment-type {
  width: 60px;
  font-size: 12px;
  font-weight: 500;
  color: var(--text-color-3);
  text-align: center;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: var(--fill-color);
  flex-shrink: 0;
}

.equipment-image {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  background-color: var(--fill-color);
  border: 1px solid var(--border-color);
  flex-shrink: 0;
}

.accessory-row .equipment-image {
  width: 40px;
  height: 40px;
}

.protection-row .equipment-image {
  width: 40px;
  height: 40px;
}

.equipment-info {
  flex: 1;
}

.equipment-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color-1);
  margin-bottom: 4px;
}

.equipment-details {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.detail-item {
  font-size: 12px;
  color: var(--text-color-3);
  background-color: var(--fill-color);
  padding: 2px 6px;
  border-radius: 3px;
}

.equipment-price {
  text-align: right;
  min-width: 80px;
}

.current-price {
  font-size: 14px;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 2px;
}

.price-change {
  font-size: 12px;
}

.price-up {
  color: var(--success-color);
}

.price-down {
  color: var(--error-color);
}

.price-same {
  color: var(--text-color-3);
}

/* 汇总信息 */
.summary-section {
  padding-top: 16px;
  border-top: 1px solid var(--border-color);
}

@media (max-width: 768px) {
  .loadout-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .header-left {
    width: 100%;
    justify-content: space-between;
  }
  
  .equipment-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .equipment-type {
    width: auto;
    align-self: flex-start;
  }
  
  .equipment-price {
    text-align: left;
  }
}
</style>